
var cacheStorageKey = 'pwa-demo-16';
var cacheList = [
    'index.html',
    'detail.html',
    'index.css',
    'js/jquery.min.js',
    'js/index.js',
    'manifest.json',
    '../news/list',
    'favicon.ico'
]

self.addEventListener('install', function(e){
    e.waitUntil(
        caches.open(cacheStorageKey)
        .then(cache => cache.addAll(cacheList))
        .then(() => self.skipWaiting())
    )
})

self.addEventListener('fetch', function(e){
    e.respondWith(
        caches.match(e.request).then(function(response){
            if (response) {
                return response;
            } else {
                caches.open(cacheStorageKey).then(cache => {
                    cache.add(e.request.url)
                })
                fetch(e.request.url)
            }
        })
    )
})

self.addEventListener('activate', function(e){
    e.waitUntil(
        caches.keys().then(cacheNames => {
            return Promise.all(
                cacheNames.filter(cacheNames => {
                   return cacheNames !== cacheStorageKey
                }).map(cacheNames => {
                    return caches.delete(cacheNames)
                })
            )
        }).then(() => {
            return self.clients.claim();
        })
    )
})